package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.*;
import com.nari.ncps.screen.mapper.dryport.*;
import com.nari.ncps.screen.service.dryport.DryportBizmgtDayService;
import com.nari.ncps.screen.service.dryport.DryportOverviewItemService;
import com.nari.ncps.screen.service.dryport.DryportProdoperThroughputService;
import com.nari.ncps.screen.service.dryport.DryportProdoperTransshipmentService;
import com.nari.ncps.screen.service.dryport.DryportProdoperTurnoverService;
import com.nari.ncps.screen.vo.dryport.OverviewVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 * 主要指标情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportOverviewItemServiceImpl extends ServiceImpl<DryportOverviewItemMapper, DryportOverviewItem> implements DryportOverviewItemService {

    @Resource
    private DryportProdoperGoodsSendMapper goodsSendMapper;

    @Resource
    private DryportProdoperOwnCoalMapper ownCoalMapper;

    @Resource
    private DryportProdoperFluxPlanMapper fluxPlanMapper;

    @Resource
    private DryportProdoperNonCoalMapper nonCoalMapper;

    @Resource
    private DryportProdoperPortGatherMapper portGatherMapper;

    @Resource
    private DryportOverviewItemMapper overviewItemMapper;

    @Resource
    private DryportBizmgtDayService bizmgtDayService;

    @Resource
    private DryportProdoperTransshipmentService Transsh;

    @Resource
    private DryportProdoperThroughputService Throughput;

    @Resource
    private DryportProdoperTurnoverService Turnover;

    @Override
    public OverviewVO getStatsByYear(Integer year) {
        Calendar calendar = Calendar.getInstance();
        // 默认获取当前年份
        if (year == null) {
            year = calendar.get(Calendar.YEAR);
        }

        // 创建VO对象并填充所有字段
        OverviewVO vo = new OverviewVO();

        // 1. 年货物发送量
        vo.setAnnualGoodsSend(getAnnualGoodsSend(year));

        // 2. 年自有煤炭运量
        vo.setAnnualOwnCoal(getAnnualOwnCoal(year));

        // 3. 年引流上线量
        vo.setAnnualFluxOnline(getAnnualFluxOnline(year));

        // 4. 年非煤运量
        vo.setAnnualNonCoal(getAnnualNonCoal(year));

        // 5. 年货物周转量
        vo.setAnnualGoodsTurnover(getAnnualGoodsTurnover(year));

        // 6. 年燃油单耗量
        vo.setAnnualFuelConsumption(getAnnualFuelConsumption(year));

        // 7. 年港口煤销量
        vo.setAnnualPortCoalSales(getAnnualPortCoalSales(year));

        // 8. 年港口倒运量
        vo.setAnnualPortTransship(getAnnualPortTransship(year));

        // 9. 年港口库存量（暂未实现）
        vo.setAnnualPortInventory(getAnnualPortInventory(year));

        // 10. 年港口吞吐量
        vo.setAnnualPortThroughput(getAnnualPortThroughput(year));

        // 11. 年港口集港量
        vo.setAnnualPortGathering(getAnnualPortGathering(year));

        return vo;
    }

    /**
     * 年货物发送量
     * 2025年11月6日
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualGoodsSend(Integer year){
        LambdaQueryWrapper<DryportProdoperGoodsSend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperGoodsSend::getYear,year)
                .eq(DryportProdoperGoodsSend::getOrgCode,100360)
                .eq(DryportProdoperGoodsSend::getDateType,0)
                .orderByDesc(DryportProdoperGoodsSend::getGoodsSendAc)
                .last("LIMIT 1");
        DryportProdoperGoodsSend item = goodsSendMapper.selectOne(queryWrapper);
        return item != null ? item.getGoodsSendAc() : null;
    }

    /**
     * 年自有煤炭运量
     * @return BigDecimal
     */
    public BigDecimal getAnnualOwnCoal(Integer year){
        LambdaQueryWrapper<DryportProdoperOwnCoal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperOwnCoal::getYear,year)
                .eq(DryportProdoperOwnCoal::getOrgCode,100360)
                .eq(DryportProdoperOwnCoal::getDateType,0)
                .orderByDesc(DryportProdoperOwnCoal::getOwnCoalPlanned)
                .last("LIMIT 1");
        DryportProdoperOwnCoal item = ownCoalMapper.selectOne(queryWrapper);
        return item != null ? item.getOwnCoalPlanned() : null;
    }

    /**
     * 年引流上线量完成量
     * @return BigDecimal
     */
    public BigDecimal getAnnualFluxOnline(Integer year){
        LambdaQueryWrapper<DryportProdoperFluxPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperFluxPlan::getYear,year)
                .eq(DryportProdoperFluxPlan::getOrgCode,100360)
                .eq(DryportProdoperFluxPlan::getDateType,0)
                .orderByDesc(DryportProdoperFluxPlan::getFluxCompleted)
                .last("LIMIT 1");
        DryportProdoperFluxPlan item = fluxPlanMapper.selectOne(queryWrapper);
        return item != null ? item.getFluxCompleted() : null;
    }

    /**
     * 年非煤运量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualNonCoal(Integer year){
        LambdaQueryWrapper<DryportProdoperNonCoal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperNonCoal::getYear,year)
                .eq(DryportProdoperNonCoal::getOrgCode,100360)
                .eq(DryportProdoperNonCoal::getDateType,0)
                .orderByDesc(DryportProdoperNonCoal::getNonCoalCompleted)
                .last("LIMIT 1");
        DryportProdoperNonCoal item = nonCoalMapper.selectOne(queryWrapper);
        return item != null ? item.getNonCoalCompleted() : null;
    }

    /**
     * 年货物周转量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualGoodsTurnover(Integer year){
        LambdaQueryWrapper<DryportProdoperTurnover> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperTurnover::getYear,year)
                .eq(DryportProdoperTurnover::getOrgCode,100360)
                .eq(DryportProdoperTurnover::getDateType,0)
                .orderByDesc(DryportProdoperTurnover::getTurnoverCompleted)
                .last("LIMIT 1");
        DryportProdoperTurnover item = Turnover.getOne(queryWrapper);
        return item != null ? item.getTurnoverCompleted() : null;
    }

    /**
     * 年燃油单耗量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualFuelConsumption(Integer year){
        LambdaQueryWrapper<DryportOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportOverviewItem::getYear,year)
                .eq(DryportOverviewItem::getOrgCode,100360)
                .eq(DryportOverviewItem::getDateType,0)
                .orderByDesc(DryportOverviewItem::getAnnualFuelConsumption)
                .last("LIMIT 1");
        DryportOverviewItem item = overviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getAnnualFuelConsumption() : null;
    }

    /**
     * 年港口煤销量（默认统计所有）
     * 取值范围：当年（当年1月1日到当年当月当日的前一天累计）
     * @param year 年份
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortCoalSales(Integer year){
        return getAnnualPortCoalSales(year, 100360, null);
    }

    /**
     * 年港口煤销量（可指定组织和销售类型）
     * 取值范围：当年（当年1月1日到当年当月当日的前一天累计）
     * @param year 年份
     * @param orgCode 组织编码（可为null，表示统计所有组织）
     * @param salesType 销售类型（可为null，表示统计所有类型）
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortCoalSales(Integer year, Integer orgCode, String salesType){
        // 默认获取当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }

        // 计算日期范围：从年初到昨天
        LocalDate startDate = LocalDate.of(year, 1, 1);
        LocalDate endDate = LocalDate.now().minusDays(1);

        // 如果查询的是未来年份，返回0
        if (year > LocalDate.now().getYear()) {
            return BigDecimal.ZERO;
        }

        // 如果查询当年但已经是1月1日，返回0（因为统计到昨天）
        if (year == LocalDate.now().getYear() && LocalDate.now().getDayOfYear() == 1) {
            return BigDecimal.ZERO;
        }

        // 格式化为 yyyyMMdd 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = startDate.format(formatter);
        String endDateStr = endDate.format(formatter);

        // 查询日期范围内的所有数据
        List<DryportBizmgtDay> dataList = bizmgtDayService.getByDateRange(startDateStr, endDateStr);

        // 累加港口煤炭销售量（根据条件过滤）
        BigDecimal totalSales = BigDecimal.ZERO;
        for (DryportBizmgtDay item : dataList) {
            // 过滤条件：组织编码
            if (orgCode != null && !orgCode.toString().equals(item.getOrgCode())) {
                continue;
            }

            // 过滤条件：销售类型
            if (salesType != null && !salesType.equals(item.getSalesType())) {
                continue;
            }

            // 累加销售量
            if (item.getPortcoalSalesVolume() != null) {
                totalSales = totalSales.add(item.getPortcoalSalesVolume());
            }
        }

        return totalSales;
    }

    /**
     * 年港口倒运量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortTransship(Integer year){
        LambdaQueryWrapper<DryportProdoperTransshipment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperTransshipment::getYear,year)
                .eq(DryportProdoperTransshipment::getOrgCode,100360)
                .eq(DryportProdoperTransshipment::getDateType,0)
                .orderByDesc(DryportProdoperTransshipment::getTransshipmentActual)
                .last("LIMIT 1");
        DryportProdoperTransshipment item = Transsh.getOne(queryWrapper);
        return item != null ? item.getTransshipmentActual() : null;
    }

    /**
     * 年港口库存量（暂未实现，返回0）
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortInventory(Integer year){
        // TODO: 待实现，暂时返回0
        return BigDecimal.ZERO;
    }

    /**
     * 年港口吞吐量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortThroughput(Integer year){
        LambdaQueryWrapper<DryportProdoperThroughput> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperThroughput::getYear,year)
                .eq(DryportProdoperThroughput::getOrgCode,100360)
                .eq(DryportProdoperThroughput::getDateType,0)
                .orderByDesc(DryportProdoperThroughput::getThroughputActual)
                .last("LIMIT 1");
        DryportProdoperThroughput item = Throughput.getOne(queryWrapper);
        return item != null ? item.getThroughputActual() : null;
    }

    /**
     * 年港口集港量
     * @param year
     * @return BigDecimal
     */
    public BigDecimal getAnnualPortGathering(Integer year){
        LambdaQueryWrapper<DryportProdoperPortGather> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportProdoperPortGather::getYear,year)
                .eq(DryportProdoperPortGather::getOrgCode,100360)
                .eq(DryportProdoperPortGather::getDateType,0)
                .orderByDesc(DryportProdoperPortGather::getGatheringCompleted)
                .last("LIMIT 1");
        DryportProdoperPortGather item = portGatherMapper.selectOne(queryWrapper);
        return item != null ? item.getGatheringCompleted() : null;
    }

}
